package com.example.demo.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TimerDemo {
    public static void main(String[] args) {
        timer1();
        timer2();
        timer3();
        timer4();
    }

    public static void timer1() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("timer1 run" + getTime());
            }
        }, 1000, 5000);//延时1s，之后每隔5s运行一次
    }

    /**
     * 每次执行时间为上一次任务开始起向后推一个时间间隔
     */
    public static void timer2() {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5);
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("timer2 run:" + getTime());
            }
        }, 1, 2, TimeUnit.SECONDS);
    }

    /**
     * 每次执行时间为上一次任务结束起向后推一个时间间隔
     */
    public static void timer3() {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5);
        executorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("timer3 run:" + getTime());
            }
        }, 1, 2, TimeUnit.SECONDS);
    }

    public static void timer4() {
        try {
            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            Scheduler scheduler = schedulerFactory.getScheduler();
            // 启动scheduler
            scheduler.start();
            // 创建HelloworldJob的JobDetail实例，并设置name/group
            JobDetail jobDetail = JobBuilder.newJob(DemoJob.class)
                    .withIdentity("myJob", "myJobGroup1")
                    //JobDataMap可以给任务传递参数
                    .usingJobData("job_param", "job_param1")
                    .build();
            // 创建Trigger触发器设置使用cronSchedule方式调度
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("myTrigger", "myTriggerGroup1")
                    .usingJobData("job_trigger_param", "job_trigger_param1")
                    .startNow()
                    //.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
                    .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ? 2019"))
                    .build();
            // 注册JobDetail实例到scheduler以及使用对应的Trigger触发时机
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private static String getTime() {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dateTime.format(formatter);
    }
}

class DemoJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("Hello world!:" + jobExecutionContext.getJobDetail().getKey());
    }
}